package com.hzh.blog.common.web;


import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.hzh.blog.common.utils.SystemContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 分页过滤器 
 * @Author:1984
 * @Written by:
 * @Creation date: 2011-3-1 下午04:36:41
 * @Version: V1.0
 * @Description:
 */
public class PagerInterceptor extends AbstractInterceptor {
	public static final String PAGE_SIZE_NAME = "ps";
	/**
	 * @Author:1984
	 * @Written by:
	 * @Creation date: 2011-3-1 下午04:36:33
	 * @Version: V1.0
	 * @Description:
	 */
	private static final long serialVersionUID = 1L;

	
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest httpRequest = ServletActionContext.getRequest();
		try{
			//取出分页参数，设置到ThreadLocal中
			SystemContext.setOffsetPri(getOffset(httpRequest));
			SystemContext.setPagesizePri(getPagesize(httpRequest));
			
			return invocation.invoke();
			
		}finally{
			SystemContext.removeOffsetPri();
			SystemContext.removePagesizePri();
		}
	}
	
	/**
	 * 从session获得分页信息
	 * @Author:1984
	 * @Written by:
	 * @Creation date: 2011-3-1 下午04:37:09
	 * @Version: V1.0
	 * @Description:
	 * @param request
	 * @return
	 */
	protected int getOffset(HttpServletRequest request){
		int offset = 0;
		try {
			offset = Integer.parseInt(request.getParameter("pager.offset"));
		} catch (Exception ignore) {
		}
		return offset;
	}
	
	/**
	 * 获得一页多少条
	 * @Author:1984
	 * @Written by:
	 * @Creation date: 2011-3-1 下午04:37:29
	 * @Version: V1.0
	 * @Description:
	 * @param request
	 * @return
	 */
	protected int getPagesize(HttpServletRequest httpRequest){
//		return 10;
		
		//首先判断request中是否有pagesize参数，如果有这个参数，证明客户端正在请求改变每页显示的行数
		String psvalue = httpRequest.getParameter("pagesize");
		if(psvalue != null && !psvalue.trim().equals("")){
			Integer ps = 0;
			try {
				ps = Integer.parseInt(psvalue);
			} catch (Exception e) {
			}
			if(ps != 0){
				httpRequest.getSession().setAttribute(PAGE_SIZE_NAME, ps);
			}
		}
		
		//判断当前session中是否有pagesize的值
		Integer pagesize = (Integer)httpRequest.getSession().getAttribute(PAGE_SIZE_NAME);
		if(pagesize == null){
			httpRequest.getSession().setAttribute(PAGE_SIZE_NAME, 9);
			return 9;
		}
		
		return pagesize;
	}

}
